package com.meisupic.copyright.support.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author lanjian
 * @version V1.0
 * @Description: TODO
 * @date 2018/3/3 21:51
 */
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

  private String defaultFailureUrl = "/login?error=true";
  private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

  @Override
  public void onAuthenticationFailure(HttpServletRequest request,
      HttpServletResponse response, AuthenticationException exception)
      throws IOException, ServletException {
    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
          "Authentication Failed: " + exception.getMessage());
    } else {
      logger.debug("Redirecting to " + defaultFailureUrl);
      redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
    }

  }

  /**
   * The URL which will be used as the failure destination.
   *
   * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp".
   */
  public void setDefaultFailureUrl(String defaultFailureUrl) {
    Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), "'"
        + defaultFailureUrl + "' is not a valid redirect URL");
    this.defaultFailureUrl = defaultFailureUrl;
  }
}
